package com.mega.common.security.filter;

import com.mega.common.core.utils.StringUtils;
import com.mega.common.security.filter.filters.AuthFilter;
import com.mega.common.security.filter.filters.RepeatableFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.DispatcherType;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class FilterConfig {

    @Value("${mega.auth.excludes}")
    private String excludes;

    @Value("${mega.auth.urlPatterns}")
    private String urlPatterns;

    /**
     * 认证过滤器
     *
     * @return
     */
    @Bean
    public FilterRegistrationBean authFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.FORWARD);
        registration.setFilter(new AuthFilter());
        registration.addUrlPatterns(StringUtils.split(urlPatterns, ","));
        registration.setName("authFilter");
        registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
        Map<String, String> initParameters = new HashMap<String, String>();
        initParameters.put("excludes", excludes);
        registration.setInitParameters(initParameters);
        return registration;
    }

    /**
     * request可重复读
     * @return
     */
    @Bean
    public FilterRegistrationBean repeatableFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new RepeatableFilter());
        registration.addUrlPatterns("/*");
        registration.setName("repeatableFilter");
        registration.setOrder(FilterRegistrationBean.HIGHEST_PRECEDENCE);
        return registration;
    }
}
